import router from "@/router";
import {Component, shallowRef} from "vue";

/**
 * tab使用的变量
 */
class TabOption {
    public path: string;
    public menuType: string;
    public title: string;
    public component: Component;
    public linkUri:string;
}

export default {
    namespaced: true,
    state() {
        return {
            tabs: new Array<TabOption>(),
            activeTabKey: null,
            breadTitles: new Array<string>(),
        }
    },
    getters: {
        tabs: state => state.tabs,
    },
    mutations: { // mutations中放同步操作，即不需要请求后端的操作
        setBreadTitles(state, breadTitles) {
            state.breadTitles = breadTitles
        },
        addTab(state, {path, title,menuType, component,linkUri}) {
            if (path === '/index') {
                state.activeTabKey = path;
                return;
            }
            //先判断是否已经存在此tab，如果已经存在就跳转过去
            let has = false;
            for (const tab of state.tabs) {
                if (tab.path === path) {
                    has = true;
                    break;
                }
            }
            if (has) {
                state.activeTabKey = path;
            } else {
                console.log(path)
                //如果没有此tab，就新增一个，并激活它
                const tabOption: TabOption = new TabOption();
                tabOption.path = path
                tabOption.title = title
                tabOption.menuType = menuType
                tabOption.linkUri = linkUri
                tabOption.component = shallowRef(component);
                // tabOption.component = component;
                state.activeTabKey = path;
                state.tabs.push(tabOption);
            }
        },
        active(state, key) {
            for (const tab of state.tabs) {
                if (tab.path === key) {
                    state.activeTabKey = key;
                    break;
                }
            }
        },
        clearSelect(state) {
            state.activeTabKey = null
        },
        removeTab(state, targetPath: string) {
            for (const tab of state.tabs) {
                if (tab.path === targetPath) {
                    const index = state.tabs.indexOf(tab);
                    state.tabs.splice(index, 1);
                    //如果关闭的是当前选中的tab，就跳转到首页
                    if (tab.path === state.activeTabKey) {
                        router.replace({path: '/index'});
                    }
                }
            }
        },
        removeAllTab(state) {
            state.tabs = new Array<TabOption>();
        }
    },
}
